import { defineStore } from 'pinia'
import { v4 as uuidv4 } from 'uuid'
import type { Node, NodeType } from '@/types/schema'

export const useEditorStore = defineStore('editor', {
  state: (): { page: Node; selectedNodeId: string | null } => ({
    page: {
      id: 'page',
      type: 'page', // 确保 type 符合 NodeType 类型
      props: {},
      children: [] as Node[]
    },
    selectedNodeId: null
  }),

  getters: {
    selectedNode: (state) => {
      if (!state.selectedNodeId) return null
      return findNodeById(state.page, state.selectedNodeId)
    }
  },

  actions: {
    selectNode(id: string) {
      this.selectedNodeId = id
    },

    addNode(type: NodeType, component?: string) {
      const newNode: Node = {
        id: uuidv4(),
        type,
        component,
        props:
          type === 'button'
            ? { text: '按钮' }
            : type === 'input'
              ? { placeholder: '请输入', value: '' }
              : type === 'container'
                ? { padding: '16px', bgColor: '#fafafa', border: true }
                : type === 'grid' || type === 'tabs'
                  ? {}
                  : type === 'custom' && component
                    ? componentRegistry.get(component)?.meta.props || {}
                    : {},
        events:
          type === 'button'
            ? { click: [{ type: 'alert', params: { message: '你好！' } }] }
            : type === 'custom' && component
              ? componentRegistry.get(component)?.meta.events
              : undefined,
        children: type === 'tabs' ? [{ id: uuidv4(), type: 'container', props: {}, children: [] }] : []
      }
      // 修复点：确保 children 是数组后再 push
      if (this.page.children) {
        this.page.children.push(newNode)
      } else {
        this.page.children = [newNode]
      }
    },

    saveToBackend() {
      console.log('保存页面:', JSON.stringify(this.page, null, 2))
      alert('已保存到控制台')
    }
  }
})

function findNodeById(node: Node, id: string): Node | null {
  if (node.id === id) return node
  if (node.children) {
    for (const child of node.children) {
      const found = findNodeById(child, id)
      if (found) return found
    }
  }
  return null
}

// Mock componentRegistry import (real one is in core/)
const componentRegistry = { get: (name: string) => ({ meta: { props: {}, events: {} } }) }
